package interceptorimpl2;



import interceptorfilterdemo.interceptorimpl.InterceptorImpl1;
import interceptorfilterdemo.interceptorimpl.InterceptorImpl2;
import interceptorimpl2.handlerimpl.HandlerImpl1;
import interceptorimpl2.interceptorimpl.Interceptor1;
import interceptorimpl2.interceptorimpl.Interceptor2;
import interceptorimpl2.interceptorimpl.Interceptor3;
import sun.util.locale.provider.FallbackLocaleProviderAdapter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by chenjun on 2017/12/18.
 */
public class HandlerChain {


    private List<Interceptor> interceptors = new ArrayList<>();

    private Handler handler = new HandlerImpl1();

    private  int interceptorIndex = -1; //记录当前执行到了哪一个拦截器，以后后续反向执行

    public HandlerChain(){
        interceptors.add(new Interceptor1());
        interceptors.add(new Interceptor2()); //这个注释掉，看另外的情况
        interceptors.add(new Interceptor3());

    }

    public  boolean applyPreHandle(){
        for(int i=0; i< interceptors.size();i++) {
            Interceptor interceptor = interceptors.get(i);
             if(interceptor.preHandle()== false) {
                 triggerAfterCompletion();
                 return false;
             }
             interceptorIndex = i;
        }
        return  true;
    }

    public  void applyPostHandle(){
        for(int i=interceptors.size()-1; i>=0 ;i--) {
            Interceptor interceptor = interceptors.get(i);
           interceptor.postHandle();
        }

    }

    private   void triggerAfterCompletion(){
        for(int i= interceptorIndex;i>=0;i--) {
            Interceptor interceptor = interceptors.get(i);
            interceptor.afterCompletion();
        }
    }


    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }
}
